package org.example.springboot.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.FileInputStream;
import java.io.IOException;

public class FTPUploadExample {

    public static void main(String[] args) {
        String server = "192.168.1.68";  // FTP 服务器地址
        int port = 21;                      // FTP 端口
        String user = "hbqzj";           // FTP 用户名
        String pass = "fengzhen";           // FTP 密码

        FTPClient ftpClient = new FTPClient();

        try {
            // 连接到 FTP 服务器
            ftpClient.connect(server, port);

            // 登录
            ftpClient.login(user, pass);

            // 检查是否成功登录
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("FTP服务器拒绝连接!");
                return;
            }

            //开启被动模式
            //ftpClient.enterLocalPassiveMode();
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);//设置传输方式为流方式
            ftpClient.setControlEncoding("UTF-8");//设置编码
            ftpClient.setBufferSize(1024 * 1024);

            // 切换到目标目录
            String remoteDir = "/home/hbqzj/ftp/upload";
            ftpClient.makeDirectory(remoteDir);
            if (!ftpClient.changeWorkingDirectory(remoteDir)) {
                System.out.println("无法将目录更改为 " + remoteDir);
                return;
            }

            // 本地文件路径
            String localFilePath = "C:\\Users\\Administrator\\Desktop\\1.jpg";
            try (FileInputStream fis = new FileInputStream(localFilePath)) {
                // 上传文件
                String remoteFileName = "123.jpg";
                boolean done = ftpClient.storeFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), fis);

                if (done) {
                    System.out.println("文件已成功上传!");
                } else {
                    System.out.println("无法上传文件!");
                    // 可以打印更详细的错误信息
                    System.out.println("FTP 服务器回复码: " + ftpClient.getReplyCode());
                    System.out.println("FTP 服务器回复信息: " + ftpClient.getReplyString());
                }

                // ...（其他代码不变）
            } catch (IOException ex) {
                System.err.println("FTP 操作发生错误: " + ex.getMessage());
                ex.printStackTrace();
            } finally {
                // 登出和断开连接
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
